﻿using System;
using System.Windows.Input;
using Present.Commands.Rx;

namespace Present.Commands.Decorators
{
    /// <summary>
    /// Schedules the Command to fire every period
    /// </summary>
    public class ScheduledCommandDecorator<TInnerCommand> : CommandDecorator<TInnerCommand> where TInnerCommand : ICommand
    {
        private IObservable<long> schedule;
        private IDisposable currentSubscription;
        private bool enabled;

        public ScheduledCommandDecorator(TInnerCommand innerCommand)
            : base(innerCommand)
        {
            enabled = true;
        }

        public IObservable<long> Schedule
        {
            get { return schedule; }
            set
            {
                StopSchedule();
                schedule = value;
                if(Enabled)
                    StartSchedule();
            }
        }

        private void StopSchedule()
        {
            if(currentSubscription != null) currentSubscription.Dispose();
            currentSubscription = null;
        }

        private void StartSchedule()
        {
            if (schedule != null)
            {

                StopSchedule();
                currentSubscription = schedule.ObserveOnUiThread().Subscribe(x => Execute(null));
            }
        }

        /// <summary>
        /// When enabled, the schedule will fire at regualar interverals
        /// When disabled, it will not
        /// </summary>
        public bool Enabled
        {
            get { return enabled; }
            set
            {
                enabled = value;
                if (enabled)
                {
                    StartSchedule();
                }
                else
                {
                    StopSchedule();
                }
            }
        }

        protected override void DisposeResources()
        {
            base.DisposeResources();
            StopSchedule();
        }
    }
}